/**
 * 
 */
package com.nexttwist;

import java.io.IOException;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.nexttwist.dao.TrackDAO;
import com.nexttwist.model.SampleTrack;

/**
 * @author HarishKumarG
 * 
 */
public class AudioRecordingFragment extends Fragment {

	private MediaRecorder myAudioRecorder;
	private String outputFile = null;
	private ImageButton mStartRecording, mStopRecording, mPlay, mStop, mSave;
	private MediaPlayer mMediaPlayer;
	private View mView;
	private TrackDAO trackDAO;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Context context = getActivity();
		trackDAO = new TrackDAO(context);
		trackDAO.open();
		
		mView = inflater.inflate(R.layout.activity_audio_recorder, container, false);

		mStartRecording = (ImageButton) mView.findViewById(R.id.btnStartRecording);
		mStopRecording = (ImageButton) mView.findViewById(R.id.btnStopRecording);

		mStop = (ImageButton) mView.findViewById(R.id.btnStopPlaying);
		mPlay = (ImageButton) mView.findViewById(R.id.btnStartPlaying);

		mSave = (ImageButton) mView.findViewById(R.id.btnSaveTrack);

		mStop.setVisibility(View.GONE);
		mStopRecording.setVisibility(View.GONE);
		mMediaPlayer = new MediaPlayer();

		mStop.setEnabled(false);
		mPlay.setEnabled(false);
		outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myrecording.3gp";

		mStartRecording.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				start(v);
			}
		});

		mStopRecording.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				stop(v);
			}
		});

		mPlay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					play();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		mStop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				stop(v);
			}
		});

		mSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					showCustomDialog();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

		mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				try {
					stopPlaying();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		return mView;
	}

	public void start(View view) {
		try {
			myAudioRecorder = new MediaRecorder();
			myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
			myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);

			outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/song_" + System.currentTimeMillis() + ".3gp";

			myAudioRecorder.setOutputFile(outputFile);
			myAudioRecorder.prepare();
			myAudioRecorder.start();
			mStartRecording.setEnabled(false);
			mStopRecording.setVisibility(View.VISIBLE);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Toast.makeText(getActivity(), "Recording started", Toast.LENGTH_LONG).show();

	}

	public void stop(View view) {
		myAudioRecorder.stop();
		myAudioRecorder.reset();
		myAudioRecorder.release();
		myAudioRecorder = null;
		mPlay.setEnabled(true);
		mStartRecording.setEnabled(true);
		mStopRecording.setVisibility(View.GONE);
		Toast.makeText(getActivity(), "Audio recorded successfully", Toast.LENGTH_LONG).show();
	}

	public void play() throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
		mMediaPlayer.setDataSource(outputFile);
		mMediaPlayer.prepare();
		mMediaPlayer.start();
		mPlay.setVisibility(View.GONE);
		mStop.setVisibility(View.VISIBLE);
		mStop.setEnabled(true);
		Toast.makeText(getActivity(), "Playing audio", Toast.LENGTH_LONG).show();
	}

	public void stopPlaying() throws Exception {
		mPlay.setVisibility(View.VISIBLE);
		mStop.setVisibility(View.GONE);
		if (null != mMediaPlayer && mMediaPlayer.isPlaying()) {
			mMediaPlayer.stop();
		}
		mMediaPlayer.reset();
	}

	public void save(String title, String album) throws Exception {
			SampleTrack track = new SampleTrack();
			track.setTrackId(1);
			track.setTrackUrl(outputFile);
			track.setTitle(title);
			track.setAlbum(album);
			track.setUserId(1);
			trackDAO.createTrack(track);

			List<SampleTrack> tracks = trackDAO.getAllTracks();
			System.out.println(tracks.size());
	}
	
	protected void showCustomDialog() {
        final Dialog dialog = new Dialog(getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.savetrackdialog);
        
        Button button = (Button)dialog.findViewById(R.id.saveTrack);    
        button.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
            	try {
            		EditText title = (EditText) dialog.findViewById(R.id.title);
                	EditText album = (EditText) dialog.findViewById(R.id.album);

					save(title.getText().toString(), album.getText().toString());
	            	
	                dialog.dismiss();
            	} catch (Exception e) {
					e.printStackTrace();
				}
            }
        });
                
        dialog.show();
    }
}
